﻿Imports Microsoft.Practices.Composite.Wpf.Regions
Imports Microsoft.Practices.Composite.Regions
Imports Infragistics.Windows.Controls
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports Infragistics.Windows.DockManager

Namespace RegionAdapters

    Public Class SplitPaneRegionAdapter
        Inherits RegionAdapterBase(Of SplitPane)

        Private m_regionTarget As SplitPane

        Protected Overrides Sub Adapt(ByVal region As Microsoft.Practices.Composite.Regions.IRegion, ByVal regionTarget As SplitPane)
            m_regionTarget = regionTarget

            'If control has child items, move them to the region and then bind control to region. Can't set ItemsSource if child items exist.
            If regionTarget.Panes.Count > 0 Then
                For Each childItem In regionTarget.Panes
                    Dim rName As String = childItem.GetValue(RegionManager.RegionNameProperty)
                    If Not String.IsNullOrEmpty(rName) Then
                        region.RegionManager.AttachNewRegion(childItem, rName)
                    End If
                    region.Add(childItem)
                Next
            End If

            regionTarget.Panes.Clear()
            AddHandler region.ActiveViews.CollectionChanged, AddressOf OnActiveViewsChanged
            For Each v As SplitPane In region.ActiveViews
                regionTarget.Panes.Add(v)
            Next

        End Sub

        Private Sub OnActiveViewsChanged(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs)
            Select Case e.Action
                Case NotifyCollectionChangedAction.Add
                    For Each v In e.NewItems
                        m_regionTarget.Panes.Add(v)
                    Next
                Case NotifyCollectionChangedAction.Remove
                    For Each v In e.OldItems
                        m_regionTarget.Panes.Remove(v)
                    Next
            End Select
        End Sub

        Protected Overrides Function CreateRegion() As Microsoft.Practices.Composite.Regions.IRegion
            Return New AllActiveRegion
        End Function

    End Class

End Namespace